package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * redission
     * @return Map<String, List<Catelog2Vo>>
     */
    public  Map<String, List<Catelog2Vo>> getCatalogJsonDbWithRedisson() {
        //RLock lock = redissonClient.getLock("CatalogJson-Lock");
        //创建读锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");
        RLock rLock = readWriteLock.readLock();
        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try {
            rLock.lock();
            //加锁成功...执行业务
            dataFromDb = getCatalogJsonFromDB();
        }finally {
            rLock.unlock();
            return dataFromDb;
        }
    }
   /* *//**
     * 从数据库查询并封装数据::分布式锁
     * @return
     *//*
    public  Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        //1、占分布式锁。去redis占坑 设置过期时间必须和加锁是同步的，保证原子性（避免死锁）
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if(lock){
            log.info("获取分布式锁成功...");
            Map<String, List<Catelog2Vo>> dataFromDb = null;
            try {
                //加锁成功...执行业务
                dataFromDb = getCatalogJsonFromDB();
            } finally {
                // lua 脚本解锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                // 删除锁
                redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList("lock"), uuid);
            }
            return dataFromDb;
        } else {
            log.info(("获取分布式锁失败...等待重试..."));
            //加锁失败...重试机制
            //休眠一百毫秒
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();     //自旋的方式
        }
    }*/

    /**
     * 查出所有的2,3级分类-redis
     * @return Map<String, List<Catelog2Vo>>
     */
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        //给缓存中放json字符串，拿出的json字符串，还要逆转为能用的对象类型（序列化与反序列化）
        //1.加入缓存逻辑，注意缓存中存放的数据是json字符串
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if(StringUtils.isEmpty(catalogJSON)){
            //2.如果缓存中没有，就查询数据库
            log.info("缓存不命中....查询数据库....");
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonDbWithRedisson();
            // 3. 查询到的数据存放到缓存中，将对象转成 JSON 存储
            redisTemplate.opsForValue().set("catalogJSON",JSON.toJSONString(catalogJsonFromDB));
            return catalogJsonFromDB;
        }
        log.info("缓存命中....");
        // 缓存中有的话就直接逆转，转 为我们指定的对象
        Map<String, List<Catelog2Vo>> stringListMap = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
        return stringListMap;
    }
    /**
     * 查出所有的2,3级分类-加缓存前,只读取数据库的操作
     * @return Map<String, List<Catelog2Vo>>
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        log.info("查询了数据库");
        // 性能优化：将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        //1.查出所有1级分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1CateLog = getParentCid(selectList, 0L);
        //2.封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1CateLog.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> level2CateLog = getParentCid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            //2.封装上面的结果
            if (level2CateLog != null) {
                catelog2Vos = level2CateLog.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.找到当前二级分类的三级分类,封装成 vo
                    List<CategoryEntity> level3CateLog = getParentCid(selectList, l2.getCatId());
                    // 三级分类有数据的情况下
                    if (level3CateLog != null) {
                        List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3CateLog.stream().map(l3 -> {
                            //2.封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, long parentCid) {
        return selectList.stream().filter(item->item.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    /**
     * 查出所有的1级分类
     * @return List<CategoryEntity>
     */
    @Cacheable(value={"category"},key="#root.method.name",sync = true)
    @Override
    public List<CategoryEntity> getLevelOneCategorys() {
        //parent_cid=0 或者 cat_level=1 都表示是一级分类。这里我们选用parent_cid=0
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2. 组装成父子的树形结构
        //找到所有的一级分类，给children设置子分类
        return categoryEntities.stream()
                 // 过滤找出一级分类
                .filter(categoryEntity -> categoryEntity.getParentCid().longValue() ==0)
                // 处理，给一级菜单递归设置子菜单
                .peek(menu-> menu.setChildren(getChildless(menu,categoryEntities)))
                // 按sort属性排序
                .sorted(Comparator.comparingInt(menu-> (menu.getSort() == null ? 0 :menu.getSort())))
                .collect(Collectors.toList());
    }


    /**
     * 递归查找所有菜单的子菜单
     */
    private List<CategoryEntity> getChildless(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                // 找到子菜单
                .peek(categoryEntity -> categoryEntity.setChildren(getChildless(categoryEntity,all)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort()==null?0:menu.getSort())))
                .collect(Collectors.toList());
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前的菜单是否被别的地方所引用
        baseMapper.deleteBatchIds(asList);
    }

    //查找当前节点的父系节点（递归查找 当前节点-->父节点-->父节点）[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        log.info("查询到的当前节点:{},完整分类路径:{}",catelogId, paths);
        return parentPath.toArray(new Long[parentPath.size()]);
    }
    //225,25,2
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        //更新关联分类：
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }


}